//
//  QZTabbarController.m
//  shortvideoplay
//
//  Created by tikeios_002 on 2024/6/18.
//

#import "QZTabbarController.h"
#import "DJBarDelegate.h"
#import "QZHomeMenceVC.h"
#import "QZFriendVC.h"
#import "QZShortPlayVC.h"
#import "DJUploadVC.h"
#import "QZMessegeVC.h"
#import "QZMyVC.h"
#import "DJMyCreatorCenterCViewController.h"
#import "QZLoginVC.h"
#import "DJNavigationController.h"
#import "UploadVideo_photosselect_cellView.h"
#import "DJUploadRequestVC.h"
#import<StoreKit/StoreKit.h>
#import "QZHongBaoView.h"
#import "Home_SystemAnnouncementView.h"

@interface QZTabbarController ()<UITabBarControllerDelegate, UITabBarDelegate,HomeSystemAnnounceDelegate>
@property (nonatomic, assign) NSInteger lastSelectIndex;
@property (nonatomic, strong) UIView *tabbarBgView;
@property (strong ,nonatomic )UploadVideo_photosselect_cellView * upload;

@property (strong ,nonatomic )Home_SystemAnnouncementView * systemView;

@property (nonatomic, strong) NSDate * lastDate;
@end

@implementation QZTabbarController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)showTextViewNavViewTo1{
    NSMutableArray * showTextViewNavViewNameArrTo1 = [NSMutableArray new];
    UIView * showTextViewNavViewViewTo1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    showTextViewNavViewViewTo1.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:showTextViewNavViewViewTo1];
    UILabel * showTextViewNavViewLabelTo1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    NSInteger showTextViewNavViewNumberTo1 = arc4random_uniform(20);
    NSLog(@"：%ld", (long)showTextViewNavViewNumberTo1);
    showTextViewNavViewLabelTo1.text = [NSString stringWithFormat:@"%ld",(long)showTextViewNavViewNumberTo1];
    [showTextViewNavViewLabelTo1 addSubview:showTextViewNavViewLabelTo1];
    
    UIImageView * showTextViewNavViewLabelTo2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [showTextViewNavViewViewTo1 addSubview:showTextViewNavViewLabelTo2];
    
}
- (void)showOldAddNavViewToMainOldView1{
    UIView * oldBgSS = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    oldBgSS.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:oldBgSS];
    
    UIButton * sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreen_W-75, kStatusBarHeight+10, 60, 46)];
    sendBtn.layer.cornerRadius = 3;
    sendBtn.backgroundColor = [UIColor whiteColor];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:ColorHex(@"#333333") forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [sendBtn addTarget:self action:@selector(sendTap) forControlEvents:UIControlEventTouchUpInside];
    [oldBgSS addSubview:sendBtn];
    
    UIView * sendBg = [[UIView alloc]initWithFrame:CGRectMake(15, kStatusBarHeight+66, KScreen_W-30, (KScreen_H-KSafeAreaBottomHeight-25-(kStatusBarHeight+66))/2)];
    sendBg.backgroundColor = [UIColor whiteColor];
    sendBg.layer.cornerRadius = 3;
    [oldBgSS addSubview:sendBg];
    
    UILabel * sendTip = [[UILabel alloc]initWithFrame:CGRectMake(0, (sendBg.frame.size.height-40)/2, sendBg.frame.size.width, 40)];
    sendTip.text = @"发送区";
    sendTip.textColor = ColorHex(@"#f0f0f0");
    sendTip.textAlignment = NSTextAlignmentCenter;
    sendTip.font = [UIFont systemFontOfSize:28];
    [sendBg addSubview:sendTip];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = COLOR(24,28,42);
    self.delegate = self;
    self.customTabbar = [QZCustomTabBar tabBarFrame:CGRectMake(0, KScreen_H - self.tabBar.frame.size.height, KScreen_W,  self.tabBar.frame.size.height) andTitles:@[NSLocalizedString(@"首页", nil),NSLocalizedString(@"分类", nil),@"",NSLocalizedString(@"消息", nil),NSLocalizedString(@"我的", nil)] selectIndex:0 changeItemBlock:^(NSInteger selectIndex) {
        
    }];
    
    [self setValue:self.customTabbar forKey:@"tabBar"];
    [self initTabbarItems];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabbarPushLogin) name:startLogin object:nil];
    
    
    _upload = [[UploadVideo_photosselect_cellView alloc]initWithFrame:CGRectMake(KScreen_W-115, kStatusBarHeight, 100, 100)];
    _upload.clipsToBounds = YES;
    _upload.layer.cornerRadius = 5;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:_upload];
    _upload.hidden = YES;
    
    KWeakSelf
    [DJUploadRequestVC share].DJUploadVStartBlock = ^(void) {
        //开始发布
        weakSelf.upload.circleView.hidden = NO;
        weakSelf.upload.UploadVideo_SelectBtn.selected = NO;
        [weakSelf.upload ShowUpload:0];
        weakSelf.upload.UploadVideo_ImageView.image = [UIImage imageWithData:[DJUploadRequestVC share].videoDatas.videoImage];
        weakSelf.upload.UploadVideo_TimeLabel.text = [Tools getTimeShow:[[DJUploadRequestVC share].videoDatas.videoTotalTime floatValue]];
        weakSelf.upload.hidden = NO;
        
    };
    [DJUploadRequestVC share].DJUploadVPrroBlock = ^(CGFloat index) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.upload ShowUpload:index/100.0];
        });
    };
    [DJUploadRequestVC share].DJUploadErrorBlock = ^(NSString * _Nonnull str) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.upload.hidden = YES;
            [weakSelf addDraft];
            [YBMsgPop showPop:str];
        });
    };
    [DJUploadRequestVC share].DJUploadSuccessBlock = ^(NSInteger index) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.upload.circleView.hidden = YES;
            weakSelf.upload.UploadVideo_SelectBtn.selected = YES;
            weakSelf.upload.UploadVideo_TimeLabel.text = @"发布成功";
            if(index == 1){
                [[BSystemAlert alloc] showActionSheetWithTitle:@"温馨提示" message:@"你首次发布作品，已被平台选中为幸运用户，去AppStore评论可立即为当前发布的作品获得流量扶持" userData:nil cancelTitle:@"取消" actions:@[@"前往"] actionBlock:^(id  _Nonnull userData, NSString * _Nonnull actionTitle) {
                    if([actionTitle isEqualToString:@"前往"]){
                        [weakSelf thumbsUpWithAppStore];
                    }
                }];
            }
            [weakSelf closeSuccessView:3.3];
        });
    };
    
    [QZHongBaoView share].hidden = YES;
       UILabel * oldshowSSSSTip2 = [[UILabel alloc]init];
    oldshowSSSSTip2.clipsToBounds = YES;
    oldshowSSSSTip2.text = @"kass显示区";
    oldshowSSSSTip2.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip2.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip2.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip2.hidden = YES;
    [self.view addSubview:oldshowSSSSTip2];
    [self.view addSubview:[QZHongBaoView share]];
    [self.view bringSubviewToFront:[QZHongBaoView share]];
    
}
- (Home_SystemAnnouncementView *)systemView{
    if(_systemView == nil){
        _systemView =[[Home_SystemAnnouncementView alloc] initWithFrame:CGRectMake(0, 0, KScreen_W, KScreen_H)];
        _systemView.cDelegate = self;
        //    _systemView.hidden = YES;
        [[UIApplication sharedApplication].keyWindow addSubview:_systemView];
    }
    return _systemView;
}
- (void)getCreatorMoneyChangeRequet{
    if([QZUserInfoModel isLogin] == NO){
        return;
    }
    if([[QZUserInfoModel share].iscreator intValue] == 1){
        return;
    }
    KMutableDic(sendDic);
    KWeakSelf
    [YBNetBase creatorHomeMoneyChangeRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
        if(code == 200){
            if(![data[@"iscreator"] boolValue] && [[[NSUserDefaults standardUserDefaults] objectForKey:@"YGSYTIP"] floatValue] != [data[@"play_money"] floatValue] && [data[@"play_money"] floatValue] != 0){
                [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%@",data[@"play_money"]] forKey:@"YGSYTIP"];
                weakSelf.systemView.hidden = NO;
                weakSelf.systemView.home_system_titleString = @"预估收益已更新";
                weakSelf.systemView.home_system_cententString = [NSString stringWithFormat:@"%@元",data[@"play_money"]];
            }
        }
    }];
}
- (void)announceViewDidClickClose:(NSInteger)view{
    _systemView.hidden = YES;
    [_systemView removeFromSuperview];
    _systemView = nil;
    if(view == 1){
        DJMyCreatorCenterCViewController * creator = [[DJMyCreatorCenterCViewController alloc]init];
        [[Tools currentActiveController].navigationController pushViewController:creator animated:YES];
    }
    
}
- (void)closeSuccessView:(CGFloat)time{
    KWeakSelf
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, time*NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.upload.hidden = YES;
        });
    });
}
- (void)thumbsUpWithAppStore {
    int x = arc4random_uniform(4);
    if(x == 0){
        if([SKStoreReviewController respondsToSelector:@selector(requestReview)]){
            [SKStoreReviewController requestReview];
            KMutableDic(sendDic)
            [YBNetBase appCommentRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
                
            }];
        }else{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPCOMENTURL] options:nil completionHandler:^(BOOL success) {
                if(success){
                    KMutableDic(sendDic)
                    [YBNetBase appCommentRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
                        
                    }];
                }
            }];
        }
    }else{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPCOMENTURL] options:nil completionHandler:^(BOOL success) {
            if(success){
                KMutableDic(sendDic)
                [YBNetBase appCommentRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
                    
                }];
            }
        }];
    }
    
}
- (void)initTabbarItems {
    [self setupChildNavigationControllerWithClass:[DJNavigationController class] rootViewControllerClass:[QZHomeMenceVC class] tag:0];
    [self setupChildNavigationControllerWithClass:[DJNavigationController class] rootViewControllerClass:[QZFriendVC class] tag:1];
//    [self setupChildNavigationControllerWithClass:[DJNavigationController class] rootViewControllerClass:[QZShortPlayVC class] tag:1];
    [self setupChildNavigationControllerWithClass:[DJNavigationController class] rootViewControllerClass:[UIViewController class] tag:2];
    [self setupChildNavigationControllerWithClass:[DJNavigationController class] rootViewControllerClass:[QZMessegeVC class] tag:3];
    [self setupChildNavigationControllerWithClass:[DJNavigationController class] rootViewControllerClass:[QZMyVC class] tag:4];
}

- (void)setupChildNavigationControllerWithClass:(Class)class rootViewControllerClass:(Class)rootViewControllerClass tag:(NSInteger)tag {

    if(tag == 2){
        [self addChildViewController:[UIViewController new]];
        return;
    }
    DJNavigationController *navVc = [[class  alloc] initWithRootViewController:[[rootViewControllerClass alloc] init]];
    navVc.delegate = [DJBarDelegate share];
    navVc.tag = tag;
    [self addChildViewController:navVc];
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if([QZUserInfoModel isLogin] == NO){
        [[QZHongBaoView share] stopClick:NO];
        [QZHongBaoView share].hidden = YES;
        [self tabbarPushLogin];
        return NO;
    }
    NSString *controllerName = NSStringFromClass(viewController.class);
    if ([controllerName isEqualToString:@"UIViewController"]) {
        [[QZHongBaoView share] stopClick:NO];
        [QZHongBaoView share].hidden = YES;
        [self tabbarUploadVideo];
        return NO;
    }
    self.lastSelectIndex = tabBarController.selectedIndex;
    [self getCreatorMoneyChangeRequet];
    return YES;
}

- (void)setDefaultSelectIndex:(NSInteger)index{
    self.selectedIndex = index;
    [self.customTabbar setDefautSelectIndex:index];
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    if(tabBarController.selectedIndex != 0){
        [[QZHongBaoView share] stopClick:NO];
        [QZHongBaoView share].hidden = YES;
    }
    
    if(tabBarController.selectedIndex == 0){
        if ([self doubleClick]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"tabbarRefishData" object:nil];
        }
    }
    
    [self.customTabbar setDefautSelectIndex:tabBarController.selectedIndex];
}
/*判断是否是双击(因为系统并没有提供双击的方法, 可以通过点击的时间间隔来判断)*/

- (BOOL)doubleClick {
    NSDate *date = [NSDate date];
    if (date.timeIntervalSince1970 - self.lastDate.timeIntervalSince1970 < 0.5) {
        //完成一次双击后，重置第一次单击的时间，区分3次或多次的单击
        self.lastDate = [NSDate dateWithTimeIntervalSince1970:0];
        return YES;
    }
    self.lastDate = date;
    return NO;
}
- (void)tabbarPushLogin{
    QZLoginVC * login = [[QZLoginVC alloc]init];
    login.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:login animated:YES completion:nil];
}
- (void)tabbarUploadVideo{
    DJUploadVC * upload = [[DJUploadVC alloc]init];
    upload.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:upload animated:YES completion:nil];
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
}
- (void)addDraft{
    NSMutableArray * arr = [NSMutableArray new];
    if([[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_%@",VIDOE_DRAFT_KEY,[QZUserInfoModel share].mid]] != nil){
        [arr addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_%@",VIDOE_DRAFT_KEY,[QZUserInfoModel share].mid]]];
    }
    
    NSMutableDictionary * dic = [NSMutableDictionary new];
    dic[@"videoImage"] = [DJUploadRequestVC share].videoDatas.videoImage;
    if([[DJUploadRequestVC share].videoDatas.videoUrl containsString:@"tmp/"]){
        NSArray * old_filearr = [[DJUploadRequestVC share].videoDatas.videoUrl componentsSeparatedByString:@"tmp/"];
        dic[@"videoUrl"] = old_filearr[1];
    }else{
        dic[@"videoUrl"] = [DJUploadRequestVC share].videoDatas.videoUrl;
    }
    dic[@"videoTotalTime"] = [DJUploadRequestVC share].videoDatas.videoTotalTime;
    dic[@"videoWdith"] = [DJUploadRequestVC share].videoDatas.videoWdith;
    dic[@"videoHeight"] = [DJUploadRequestVC share].videoDatas.videoHeight;
    
    if([DJUploadRequestVC share].videoDatas.videoContent != nil){
        dic[@"videoContent"] = [DJUploadRequestVC share].videoDatas.videoContent;
    }else{
        dic[@"videoContent"] = @"";
    }
    if([DJUploadRequestVC share].videoDatas.videoLabels != nil){
        dic[@"videoLabels"] = [DJUploadRequestVC share].videoDatas.videoLabels;
    }else{
        dic[@"videoLabels"] = @"";
    }
    if([DJUploadRequestVC share].videoDatas.saveTime != nil){
        dic[@"saveTime"] = [DJUploadRequestVC share].videoDatas.saveTime;
    }else{
        dic[@"saveTime"] = [Tools getNowDayTimeTimestamp];
    }
    if([[DJUploadRequestVC share].videoDatas.isDown boolValue]){
        dic[@"isDown"] = @(1);
    }else{
        dic[@"isDown"] = @(0);
    }
    if([[DJUploadRequestVC share].videoDatas.isMineSee boolValue]){
        dic[@"isMineSee"] = @(1);
    }else{
        dic[@"isMineSee"] = @(0);
    }
    
    [arr insertObject:dic atIndex:0];
    [[NSUserDefaults standardUserDefaults] setValue:arr forKey:[NSString stringWithFormat:@"%@_%@",VIDOE_DRAFT_KEY,[QZUserInfoModel share].mid]];
}
@end
